package net.ifilm.aop;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;

import java.util.Arrays;

/**
 * CreateBy: <a href="wangjunneil@gmail.com">Calvin</a>
 * CreateTime: 2013-01-16 00:20
 */
public class LoggingAroundAdvice implements MethodInterceptor {

    /**
     * 日志对象引用
     */
    private static Log log = LogFactory.getLog(LoggingAroundAdvice.class);

    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        if (log.isInfoEnabled()) {
            log.info("The method " + methodInvocation.getMethod().getName()
                + "() begins with "
                + Arrays.toString(methodInvocation.getArguments()));
        }

        try {
            Object result = methodInvocation.proceed();

            if (log.isInfoEnabled()) {
                log.info("The method " + methodInvocation.getMethod().getName()
                    + "() ends with " + result);
            }

            return result;
        } catch (IllegalArgumentException e) {
            if (log.isErrorEnabled()) {
                log.error("Illegal argument "
                    + Arrays.toString(methodInvocation.getArguments())
                    + " for method " + methodInvocation.getMethod().getName()
                    + "()");
            }

            throw e;
        }
    }

}
